package com.mf.morefun.ui.myclass;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.adapter.ClassListAdapter;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.AliInfoBean;
import com.mf.morefun.bean.ClassListBean;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.PMUserBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestAddClassBean;
import com.mf.morefun.requestbean.RequestClassBean;
import com.mf.morefun.requestbean.RequestEditClassBean;
import com.mf.morefun.requestbean.RequestUserBean;
import com.mf.morefun.ui.moreread.ListenRecordActivity;
import com.mf.morefun.ui.personnelmanagement.PersonnelManagementActivity;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.StorageUtil;
import com.mf.morefun.util.UploadUtil;
import com.mf.morefun.widget.BackIdeaPop;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;
import com.zhcx.zhcxlibrary.utils.permission.Request;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClassListActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_class)
    ImageView ivClass;
    @BindView(R.id.iv_edit)
    ImageView ivEdit;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.gv_class)
    GridView gvClass;
    private SPUtils mSputils;
    private List<ClassListBean> mClassList = new ArrayList<>();
    private ClassListAdapter adapter;
    private boolean isCanEdit = false;
    private RoundProcessDialog dialog;
    private String classId = "";
    private int clickPosition = 0;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_classlist;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSputils = new SPUtils(getApplicationContext());
        EventBus.getDefault().register(this);
        dialog = new RoundProcessDialog(ClassListActivity.this, "正在上传中...");
        adapter = new ClassListAdapter(ClassListActivity.this, mClassList);
        gvClass.setAdapter(adapter);
        initGetClass();
        gvClass.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != mClassList && mClassList.size() > 0) {
                    if (isCanEdit){//这里是编辑状态
                        clickPosition = position;
                        classId = mClassList.get(position).getClassBelong().getId();
                        mSputils.putString(Configuration.CLASSIMAGE, mClassList.get(position).getClassBelong().getCover());
                        mSputils.putString(Configuration.CLASSNAME, mClassList.get(position).getClassBelong().getName());
                        try {
                            showPop(mClassList, position);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }else {
                        Intent mIntent = new Intent(ClassListActivity.this, ClassDetailActivity.class);
                        mIntent.putExtra("CLASSBENA", mClassList.get(position));
                        startActivity(mIntent);
                    }
                }
            }
        });
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSputils.getString(Configuration.USERPHONE), mSputils.getString(Configuration.USERPASSWORD));
        }else {
            if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getUserType())){
                ivEdit.setVisibility(View.GONE);
                ivAdd.setVisibility(View.GONE);
            }else {
                if (MoreFunApplication.loginBean.getResult().getUserType().equals("3")){

                    initGetAliInfo();

                    ivEdit.setVisibility(View.VISIBLE);
                    ivAdd.setVisibility(View.VISIBLE);
                }else {
                    ivEdit.setVisibility(View.GONE);
                    ivAdd.setVisibility(View.GONE);
                }
            }
            ivAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showChangeName(1);
                }
            });
            ivEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isCanEdit){
                        isCanEdit = false;
                        ivEdit.setImageResource(R.mipmap.classedit);
                    }else {
                        isCanEdit = true;
                        ivEdit.setImageResource(R.mipmap.classcanedit);
                    }
                }
            });
        }
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("DELETECLASS");
        mFilter.addAction("GETUSERINFO");
        registerReceiver(mReceiver, mFilter);


    }

    private void initGetAliInfo() {
        RequestParams params = new RequestParams(com.mf.morefun.constant.Configuration.HOST + com.mf.morefun.constant.Configuration.GETALIINFOV2);

        PMUserBean.CountryBean countrybean = new PMUserBean.CountryBean();
        countrybean.setId( MoreFunApplication.loginBean.getResult().getCountry().getId());
        params.setBodyContent(JSON.toJSONString(countrybean));

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    AliInfoBean aliInfoBean = JSON.parseObject(result, AliInfoBean.class);
                    if (aliInfoBean.getStatusCode() == 200) {
                        mSputils.putString(com.mf.morefun.constant.Configuration.ACCESSKEYID, aliInfoBean.getAccessKeyId());
                        mSputils.putString(com.mf.morefun.constant.Configuration.ACCESSKEYSECRET, aliInfoBean.getAccessKeySecret());
                        mSputils.putString(com.mf.morefun.constant.Configuration.SECURITYTOKEN, aliInfoBean.getSecurityToken());

                        mSputils.putString(com.mf.morefun.constant.Configuration.ENDPOINT, aliInfoBean.getEndPoint());
                        mSputils.putString(com.mf.morefun.constant.Configuration.BUCKETNAME, aliInfoBean.getBucketName());
                        mSputils.putString(com.mf.morefun.constant.Configuration.BUCKETDOMAIN, aliInfoBean.getBucketDomain());
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("DELETECLASS")) {
                initDeleteClass(mClassList, intent.getIntExtra("POSITION", 0));
            }else if(intent.getAction().equals("GETUSERINFO")){
                if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getUserType())){
                    ivEdit.setVisibility(View.GONE);
                    ivAdd.setVisibility(View.GONE);
                }else {
                    if (MoreFunApplication.loginBean.getResult().getUserType().equals("3")){
                        ivEdit.setVisibility(View.VISIBLE);
                        ivAdd.setVisibility(View.VISIBLE);
                    }else {
                        ivEdit.setVisibility(View.GONE);
                        ivAdd.setVisibility(View.GONE);
                    }
                }
                ivAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showChangeName(1);
                    }
                });
                ivEdit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isCanEdit){
                            isCanEdit = false;
                            ivEdit.setImageResource(R.mipmap.classedit);
                        }else {
                            isCanEdit = true;
                            ivEdit.setImageResource(R.mipmap.classcanedit);
                        }
                    }
                });
            }
        }
    };

    private void initDeleteClass(List<ClassListBean> mClassList, int position) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.DELETECLASS);
        RequestUserBean userBean = new RequestUserBean();
        userBean.setId(mClassList.get(position).getClassBelong().getId());
        params.setBodyContent(JSON.toJSONString(userBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)){
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0){
                        mClassList.remove(position);
                        adapter.notifyDataSetChanged();
                    }else {
                        ToastUtils.show(getApplicationContext(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(mReceiver);
        }catch (Exception e){
            e.printStackTrace();
        }
        EventBus.getDefault().unregister(this);
    }

    private PopupWindow mNamePop = null;

    //改名字
    private void showChangeName(int type) {//0为编辑  1位新增
        try {
            if (null == mNamePop) {
                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.layout_popclass, null);
                // 这里启动头像
                RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
                rl_bg.getBackground().setAlpha(100);
                EditText edit_name = view.findViewById(R.id.edit_name);
                edit_name.setHint("请输入班级名称");
                ImageView iv_cancel = view.findViewById(R.id.iv_cancel);
                iv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mNamePop.dismiss();
                        mNamePop = null;
                    }
                });
                ImageView iv_sure = view.findViewById(R.id.iv_sure);
                iv_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (StringUtils.isEmpty(edit_name.getText().toString())){
                            ToastUtils.show(getApplicationContext(), "请输入班级名称", 100);
                            return;
                        }
                        mNamePop.dismiss();
                        mNamePop = null;
                        mSputils.putString(Configuration.CLASSNAME, edit_name.getText().toString());
                        if (type == 0){
                            initEditClass(mSputils.getString(Configuration.CLASSNAME), mSputils.getString(Configuration.CLASSIMAGE));
                        }else {
                            initAddClass(mSputils.getString(Configuration.CLASSNAME));
                        }
                    }
                });
                mNamePop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                mNamePop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                mNamePop.setBackgroundDrawable(new BitmapDrawable());
                mNamePop.setFocusable(true);
                mNamePop.update();
                mNamePop.showAtLocation(view, Gravity.CENTER, 0, 0);
                mNamePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        mNamePop.dismiss();
                        mNamePop = null;
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void initAddClass(String name) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.ADDCLASS);
        RequestAddClassBean requestAddClassBean = new RequestAddClassBean();
        requestAddClassBean.setName(name);
        RequestAddClassBean.OrganBean organBean = new RequestAddClassBean.OrganBean();
        organBean.setId(MoreFunApplication.loginBean.getResult().getOrgan().getId());
        requestAddClassBean.setOrgan(organBean);
        params.setBodyContent(JSON.toJSONString(requestAddClassBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)){
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0){
                        if (!StringUtils.isEmpty(mResult.getResult())){
                            ClassListBean.ClassBelongBean classBelongBean = JSON.parseObject(mResult.getResult(), ClassListBean.ClassBelongBean.class);
                            ClassListBean classListBean = new ClassListBean();
                            classListBean.setClassBelong(classBelongBean);
                            mClassList.add(classListBean);
                            adapter.notifyDataSetChanged();
                        }
                    }else {
                        ToastUtils.show(getApplicationContext(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private PopupWindow mDoPop;
    //弹出操作的弹框   需要三个按钮   设置有效期， 重置密码， 删除用户
    private void showPop(List<ClassListBean> mClassList, int position) {
        if (null == mDoPop) {
            View view = LayoutInflater.from(ClassListActivity.this).inflate(R.layout.layout_classdo, null);
            RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_name = view.findViewById(R.id.tv_name);//修改名称
            tv_name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    showChangeName(0);
                }
            });
            TextView tv_image = view.findViewById(R.id.tv_image);
            tv_image.setOnClickListener(new View.OnClickListener() {//修改图片
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    try {
                        showChangeHead();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
            TextView tv_deleteclass = view.findViewById(R.id.tv_deleteclass);
            tv_deleteclass.setOnClickListener(new View.OnClickListener() {//删除班级
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    //
                    BackIdeaPop pops = new BackIdeaPop(ClassListActivity.this);
                    pops.showPop("确定要删除 " + mClassList.get(position).getClassBelong().getName() + "吗?", 6, position);
                }
            });
            TextView tvCancel = view.findViewById(R.id.tv_cancel);
            tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                }
            });
            mDoPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            mDoPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mDoPop.setBackgroundDrawable(new BitmapDrawable());
            mDoPop.setFocusable(true);
            mDoPop.update();
            mDoPop.showAtLocation(view, Gravity.CENTER, 0, 0);
            mDoPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mDoPop.dismiss();
                    mDoPop = null;
                }
            });
        }
    }

    private PopupWindow mHeadPop = null;
    /**
     * 显示底部栏
     */
    private void showChangeHead() {
        if (mHeadPop == null) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_pophead, null);
            // 这里启动头像
            RelativeLayout rl_bg = (RelativeLayout) view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_camara = (TextView) view.findViewById(R.id.tv_camara);
            tv_camara.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (StorageUtil.camearaUtil(ClassListActivity.this)){
                        CallSystemCamera();
                    }else {
                        showMissingPermissionDialog();
                    }
                    mHeadPop.dismiss();
                    mHeadPop = null;
                }
            });
            TextView tv_bendi = (TextView) view.findViewById(R.id.tv_bendi);
            tv_bendi.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    CallSystemPhoto();
                    mHeadPop.dismiss();
                    mHeadPop = null;
                }
            });
            TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    mHeadPop.dismiss();
                    mHeadPop = null;
                }
            });
            int h = getWindowManager().getDefaultDisplay().getHeight();
            mHeadPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, h);
            mHeadPop.setFocusable(true);
            mHeadPop.setOutsideTouchable(true);
            mHeadPop.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                    return false;
                }
            });
            mHeadPop.setBackgroundDrawable(new BitmapDrawable());
            Rect rect = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int winHeight = getWindow().getDecorView().getHeight();
            mHeadPop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, winHeight - rect.bottom);
        }
    }

    private String mFilePath;

    //调用系统相机
    private void CallSystemCamera() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//调用android自带的照相机
            long time = System.currentTimeMillis();
            Date date = new Date(time);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            mFilePath = Environment.getExternalStorageDirectory() + "/" + sdf.format(date) + ".jpg";
            // 加载路径
            Uri uri = Uri.fromFile(new File(mFilePath));
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            // 指定存储路径，这样就可以保存原图了
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, 1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 显示缺失权限提示
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ClassListActivity.this);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startAppSettings();
            }
        });

        builder.show();
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }


    //调用本地相册
    private void CallSystemPhoto() {
        try {
            Intent intent = null;
            if (DeviceUtils.getPhoneBrand().contains("meizu")) {
                intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            } else {
                intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
            }
            startActivityForResult(intent, 2);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                options.inSampleSize = 10;
//				 把流解析成bitmap
                Bitmap bitmap = BitmapFactory.decodeFile(mFilePath, options);
//                mUserdetailUserheader.setImageBitmap(bitmap);
                File file = new File(mFilePath);
                String path = file.getAbsolutePath();
                if (null != dialog && !dialog.isShow()){
                    dialog.show();
                }
                UploadUtil uploadUtil = new UploadUtil();
                uploadUtil.uploadFile(ClassListActivity.this,
                        mSputils.getString(Configuration.ACCESSKEYID),
                        mSputils.getString(Configuration.ACCESSKEYSECRET),
                        mSputils.getString(Configuration.SECURITYTOKEN),
                        mSputils.getString(Configuration.ENDPOINT),
                        mSputils.getString(Configuration.BUCKETNAME),

                        System.currentTimeMillis() + "androidimg.jpg",
                        path, false);
            } else if (requestCode == 2) {
                if (data != null) {
                    Uri uri = data.getData();
                    String path = "";
                    if (!TextUtils.isEmpty(uri.getAuthority())) {
                        Cursor cursor = getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                        if (null == cursor) {
                            ToastUtils.show(getApplicationContext(), "", ToastUtils.LENGTH_SHORT);
                            return;
                        }
                        cursor.moveToFirst();
                        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                        options.inSampleSize = 10;
//						 把流解析成bitmap
                        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
                        cursor.close();
                        if (null != dialog && !dialog.isShow()){
                            dialog.show();
                        }
                        //上传文件
                        UploadUtil uploadUtil = new UploadUtil();
                        uploadUtil.uploadFile(ClassListActivity.this,
                                mSputils.getString(Configuration.ACCESSKEYID),
                                mSputils.getString(Configuration.ACCESSKEYSECRET),
                                mSputils.getString(Configuration.SECURITYTOKEN),
                                mSputils.getString(Configuration.ENDPOINT),
                                mSputils.getString(Configuration.BUCKETNAME),
                                System.currentTimeMillis() + "androidimg.jpg",
                                path, false);
                    }
                }
            }
        }
    }

    //接受RecordMusicService发过来的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicMessage(EventMessageBean message) {
        if(message.getType() == 101){
           // String host = Configuration.OOSROOT;// "http://morefunreadingproduct.oss-cn-shanghai.aliyuncs.com/";

            String host =  mSputils.getString(Configuration.BUCKETDOMAIN);

            mSputils.putString(Configuration.CLASSIMAGE, (host + message.getFileName()));
            //开始上传
            initEditClass(mSputils.getString(Configuration.CLASSNAME), mSputils.getString(Configuration.CLASSIMAGE));
        }else if(message.getType() == 102){
            ToastUtils.show(getApplicationContext(), "上传失败", 100);
        }
        if (null != dialog && dialog.isShow()){
            dialog.cancel();
        }
    }

    private void initEditClass(String name, String cover) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.EDITCLASS);
        RequestEditClassBean requestEditClassBean = new RequestEditClassBean();
        requestEditClassBean.setCover(cover);
        requestEditClassBean.setName(name);
        requestEditClassBean.setId(classId);
        RequestEditClassBean.OrganBean organBean = new RequestEditClassBean.OrganBean();
        organBean.setId(MoreFunApplication.loginBean.getResult().getOrgan().getId());
        requestEditClassBean.setOrgan(organBean);
        params.setBodyContent(JSON.toJSONString(requestEditClassBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)){
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0){
                        mClassList.get(clickPosition).getClassBelong().setName(name);
                        mClassList.get(clickPosition).getClassBelong().setCover(cover);
                        adapter.notifyDataSetChanged();
                    }else {
                        ToastUtils.show(getApplicationContext(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initGetClass() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.CLASSLIST);
        RequestClassBean requestClassBean = new RequestClassBean();
        RequestClassBean.UserBean userBean = new RequestClassBean.UserBean();
        userBean.setId(mSputils.getString(Configuration.USERID));
        requestClassBean.setUser(userBean);
        params.setBodyContent(JSON.toJSONString(requestClassBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mClassList.clear();
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            List<ClassListBean> classListBeanList = JSON.parseArray(resultBean.getResult(), ClassListBean.class);
                            mClassList.addAll(classListBeanList);
                        } else {
                            ToastUtils.show(getApplicationContext(), "数据为空", 100);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(ClassListActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    @Override
    protected void initData() {

    }


    @OnClick(R.id.iv_back)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }
}
